package com.weifly.weistock.core.util;

import com.weifly.weistock.bo.record.AbstractRecordBO;
import com.weifly.weistock.bo.record.RecordPairBO;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 工具类
 *
 * @author weifly
 * @since 2020/01/16
 */
public class RecordUtils {

    public static void sortRecordList(List<? extends AbstractRecordBO> recordList) {
        recordList.sort((r1, r2) -> {
            int compareValue = r1.getDate().compareTo(r2.getDate());
            if (compareValue == 0) {
                // 日期相同，比较时间
                compareValue = r1.getTime().compareTo(r2.getTime());
                if (compareValue == 0) {
                    // 时间相同，比较委托号
                    compareValue = r1.getEntrustCode().compareTo(r2.getEntrustCode());
                }
            }
            return compareValue;
        });
    }

    public static void clearRecordPair(List<? extends AbstractRecordBO> recordList) {
        for (AbstractRecordBO record : recordList) {
            if (record.getPairList() != null) {
                record.getPairList().clear();
            }
            record.setDiffAmount(null);
        }
    }

    public static String makePairAttr(List<RecordPairBO> pairList, int tradeNumber) {
        if (pairList == null || pairList.isEmpty()) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < pairList.size(); i++) {
            RecordPairBO pair = pairList.get(i);
            // 输出index
            if (pair.getNumber() == tradeNumber) {
                sb.append(pair.getIndex());
            } else {
                sb.append(pair.getIndex());
                if (pair.getNumber() > 1) {
                    sb.append("(").append(pair.getNumber()).append(")");
                }
            }
            // 输出分隔符
            if (i < pairList.size() - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    public static List<RecordPairBO> parsePairAttr(String pairAttr, int tradeNumber) {
        if (StringUtils.isBlank(pairAttr)) {
            return null;
        }
        List<RecordPairBO> pairList = new ArrayList<>();
        String[] parts = pairAttr.split(",");
        for (String p : parts) {
            RecordPairBO pair = new RecordPairBO();
            if (p.indexOf("(") == -1) {
                pair.setIndex(Integer.parseInt(p));
                pair.setNumber(tradeNumber);
            } else {
                int startIdx = p.indexOf("(");
                int endIdx = p.indexOf(")");
                pair.setIndex(Integer.parseInt(p.substring(0, startIdx)));
                pair.setNumber(Integer.parseInt(p.substring(startIdx + 1, endIdx)));
            }
            pairList.add(pair);
        }
        return pairList;
    }
}
